package service

import (
	"context"
	"database/sql"
	"time"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/userInfo/glb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) UpdateInfo(ctx context.Context, request *pb.UpdateInfoRequest) (*pb.UpdateInfoResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.UpdateInfoResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	user := &models.User{AccountID: token.AccountID}

	err = glb.DB.Select("account_id").Take(user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.UpdateInfoResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "用户不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return updateInfoRespSvrErr, nil
	}

	user.Name = sql.NullString{String: request.GetName(), Valid: true}
	user.Gender = sql.NullInt32{Int32: request.GetGender(), Valid: true}

	err = glb.DB.Model(user).Updates(user).Error
	if err != nil {
		glb.Logger.Error(err.Error())
		return updateInfoRespSvrErr, nil
	}

	token = &core.Token{
		Timestamp: time.Now().Unix(),
		LifeCycle: core.TokenTimeout,
		AccountID: user.AccountID,
		Name:      user.Name.String,
		Gender:    user.Gender.Int32,
		Type:      user.Type.Int32,
	}
	tokenStr := token.PackToken(glb.TokenCert)

	return &pb.UpdateInfoResponse{
		Status:   &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		NewToken: tokenStr,
	}, nil
}
